import request from '../../util/request'
let userinfo = localStorage.getItem('userinfo')
try {
  userinfo = JSON.parse(userinfo) || []
} catch (err) {
  userinfo = []
}

function updateStorage(key, data) {
  if (typeof data === 'object') {
    data = JSON.stringify(data)
  }
  localStorage.setItem(key, data)
}

export default {
  namespaced: true,
  state: {
    userinfo,
    length: 0
  },
  mutations: {
    //   登录
    log(state, payload) {
      state.userinfo = payload;
      updateStorage('userinfo', payload)
    },
    unlog(state, payload) {
      state.userinfo = {};
      localStorage.removeItem('userinfo');
      localStorage.removeItem('cartlist')
    },
    changelength(state, payload) {
      state.length = payload
    }
  },
  actions: {
    async cartlength(context, payload) {
      if (payload && payload.user_id) {
        const {
          data: {
            data
          }
        } = await request.get('/api/cart/' + payload.user_id, {
          headers: {
            authorization: payload.authorization
          }
        })
        context.commit('changelength',data.length)
      }
    }
  },
  modules: {},
  getters: {
    //   判断是否登录，返回true or false
    islog(state) {
      return !!state.userinfo.authorization
    }
  }
}